<template>
  <div class="user-management">
    <el-card class="permission-card">
      <template #header>
        <div class="card-header">
          <span>权限配置</span>
          <el-button type="primary" @click="initializePermissions">初始化权限</el-button>
        </div>
      </template>
      
      <el-tabs type="border-card">
        <el-tab-pane label="学生权限">
          <el-form :model="permissions" label-width="120px">
            <el-form-item label="编辑信息">
              <el-switch v-model="permissions.studentEdit" @change="(val) => updatePermission('student', 'edit', val)" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="教师权限">
          <el-form :model="permissions" label-width="120px">
            <el-form-item label="编辑信息">
              <el-switch v-model="permissions.teacherEdit" @change="(val) => updatePermission('teacher', 'edit', val)" />
            </el-form-item>
            <el-form-item label="查看学生成绩">
              <el-switch 
                v-model="permissions.teacherScore" 
                @change="(val) => updatePermission('teacher', 'score', val)"
                active-text="允许教师查看学生成绩" 
              />
            </el-form-item>
            <el-form-item label="修改学生成绩">
              <el-switch 
                v-model="permissions.teacherAdmin" 
                @change="(val) => updatePermission('teacher', 'admin', val)"
                active-text="允许教师修改学生成绩"
                :disabled="!permissions.teacherScore"
              />
              <div v-if="!permissions.teacherScore" style="color: #909399; font-size: 12px; margin-top: 4px;">
                注意：需要先启用"查看学生成绩"权限
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
        </div>
      </template>

      <!-- 表格 -->
      <el-table
        :data="users"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="stuteaid" label="学号/工号" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.role)">
              {{ getRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="权限状态" width="200">
          <template #default="scope">
            <div v-if="scope.row.role === 'student'">
              <el-tag :type="permissions.studentEdit ? 'success' : 'danger'" size="small">
                {{ permissions.studentEdit ? '可编辑' : '不可编辑' }}
              </el-tag>
            </div>
            <div v-if="scope.row.role === 'teacher'" class="teacher-permissions">
              <el-tag :type="permissions.teacherEdit ? 'success' : 'danger'" size="small" style="margin-right: 4px;">
                {{ permissions.teacherEdit ? '可编辑' : '不可编辑' }}
              </el-tag>
              <el-tag :type="permissions.teacherScore ? 'success' : 'danger'" size="small" style="margin-right: 4px;">
                {{ permissions.teacherScore ? '可查看成绩' : '不可查看成绩' }}
              </el-tag>
              <el-tag :type="(permissions.teacherScore && permissions.teacherAdmin) ? 'success' : 'danger'" size="small">
                {{ (permissions.teacherScore && permissions.teacherAdmin) ? '可修改成绩' : '不可修改成绩' }}
              </el-tag>
            </div>
            <div v-if="scope.row.role === 'admin'">
              <el-tag type="success" size="small">完全权限</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { getPermissions, updatePermission as updatePermissionAPI, initializePermissions as initPermissionsAPI } from '@/api/permission'

export default {
  name: 'UserManagement',
  setup() {
    const loading = ref(false)
    const users = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    const fetchUsers = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/Login/getAllUsers')
        if (response.data.code === 1) {
          users.value = response.data.data
          total.value = users.value.length
        } else {
          ElMessage.error('获取用户列表失败')
        }
      } catch (error) {
        ElMessage.error('获取用户列表失败')
        console.error('获取用户列表错误:', error)
      } finally {
        loading.value = false
      }
    }



    const getRoleType = (role) => {
      switch (role) {
        case 'admin': return 'danger'
        case 'teacher': return 'warning'
        case 'student': return 'success'
        default: return 'info'
      }
    }

    const getRoleText = (role) => {
      switch (role) {
        case 'admin': return '管理员'
        case 'teacher': return '教师'
        case 'student': return '学生'
        default: return '未知'
      }
    }

    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }



    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    // 权限管理相关
    const permissions = reactive({
      studentEdit: true,
      teacherEdit: true,
      teacherScore: true,
      teacherAdmin: true
    })

    const fetchPermissions = async () => {
      try {
        const response = await getPermissions()
        if (response.data.code === 1) {
          const permissionData = response.data.data
          Object.keys(permissionData).forEach(key => {
            if (permissions.hasOwnProperty(key)) {
              permissions[key] = permissionData[key]
            }
          })
        }
      } catch (error) {
        console.error('获取权限配置失败:', error)
        ElMessage.error('获取权限配置失败')
      }
    }

    const updatePermission = async (role, type, value) => {
      try {
        const response = await updatePermissionAPI(role, type, value)
        if (response.data.code === 1) {
          ElMessage.success('权限更新成功')
        } else {
          ElMessage.error(response.data.msg || '权限更新失败')
        }
      } catch (error) {
        console.error('更新权限失败:', error)
        ElMessage.error('更新权限失败')
      }
    }

    const initializePermissions = async () => {
      try {
        const response = await initPermissionsAPI()
        if (response.data.code === 1) {
          ElMessage.success('权限初始化成功')
          await fetchPermissions()
        } else {
          ElMessage.error(response.data.msg || '权限初始化失败')
        }
      } catch (error) {
        console.error('初始化权限失败:', error)
        ElMessage.error('初始化权限失败')
      }
    }

    onMounted(() => {
      fetchUsers()
      fetchPermissions()
    })

    return {
      loading,
      users,
      currentPage,
      pageSize,
      total,
      fetchUsers,
      permissions,
      updatePermission,
      initializePermissions,
      getRoleType,
      getRoleText,
      formatDate,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
}

.batch-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.teacher-permissions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.teacher-permissions .el-tag {
  margin-bottom: 2px;
}
</style>


